package com.splant.android.smart.UILevel.Community;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.ModelLevel.TimerWater;
import com.splant.android.smart.ModelLevel.TimerWaterListBean;
import com.splant.android.smart.ModelLevel.WaterListBean;
import com.splant.android.smart.ModelLevel.event.PostWater;
import com.splant.android.smart.ModelLevel.sPlantRequestParams;
import com.splant.android.smart.SystemDefinedLevel.DeciveManager.DeviveMessages;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.CustomDialog;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.LoadingDialog;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.WheelView.WheelView;
import com.splant.android.smart.UILevel.Utils.sPlantUitl;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import android.os.Handler;

import de.greenrobot.event.EventBus;

public class Garden_Water_Activity extends Activity implements View.OnClickListener {


    private TextView tv_waterName0;
    private TextView tv_switch0;
    private ImageView img_switch0Selected;
    private TextView tv_switch1;
    private ImageView img_switch1Selected;
    private TextView tv_switch2;
    private ImageView img_switch2Selected;

    private Button btn_open;
    private Button btn_close;

    private TextView tv_waterName1;
    private TextView tv_waterId;
    private TextView tv_rainStopSwitch;

    private TextView tv_s0;
    private TextView tv_s1;
    private TextView tv_s2;

    private WaterListBean.Water water;
    private int deviceType;
    private int selectedDay=0;
    private int selectedSwitchNo = 1;

    private ListView lv_timerWaters;
    private TextView tv_month1;
    private TextView tv_month2;
    private TextView tv_month3;
    private TextView tv_month4;
    private TextView tv_month5;
    private TextView tv_month6;
    private TextView tv_month7;
    private TextView tv_month8;
    private TextView tv_month9;
    private TextView tv_month10;
    private TextView tv_month11;
    private TextView tv_month12;
    private TextView tv_month13;
    private TextView tv_month14;
    private TextView tv_month15;
    private TextView tv_month16;
    private TextView tv_month17;
    private TextView tv_month18;
    private TextView tv_month19;
    private TextView tv_month20;
    private TextView tv_month21;
    private TextView tv_month22;
    private TextView tv_month23;
    private TextView tv_month24;
    private TextView tv_month25;
    private TextView tv_month26;
    private TextView tv_month27;
    private TextView tv_month28;
    private TextView tv_month29;
    private TextView tv_month30;
    private TextView tv_month31;

    private MaterialRefreshLayout materialRefreshLayout;
    private String waterSwitchsNo = "";//浇水选择了的开关
    private LinearLayout ll_waterContent;
    private Button btn_goBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.garden_water_activity);

        water = (WaterListBean.Water) getIntent().getSerializableExtra("water");

        if (water == null)
            return;

        materialRefreshLayout = (MaterialRefreshLayout) findViewById(R.id.refresh);
        btn_goBack = (Button) findViewById(R.id.btn_goBack);

        tv_waterName0 = (TextView) findViewById(R.id.tv_waterName0);
        ll_waterContent = (LinearLayout) findViewById(R.id.ll_waterContent);
        lv_timerWaters = (ListView) findViewById(R.id.lv_timerWaters);

        tv_month1 = (TextView) findViewById(R.id.tv_month1);
        tv_month2 = (TextView) findViewById(R.id.tv_month2);
        tv_month3 = (TextView) findViewById(R.id.tv_month3);
        tv_month4 = (TextView) findViewById(R.id.tv_month4);
        tv_month5 = (TextView) findViewById(R.id.tv_month5);
        tv_month6 = (TextView) findViewById(R.id.tv_month6);
        tv_month7 = (TextView) findViewById(R.id.tv_month7);
        tv_month8 = (TextView) findViewById(R.id.tv_month8);
        tv_month9 = (TextView) findViewById(R.id.tv_month9);
        tv_month10 = (TextView) findViewById(R.id.tv_month10);
        tv_month11 = (TextView) findViewById(R.id.tv_month11);
        tv_month12 = (TextView) findViewById(R.id.tv_month12);
        tv_month13 = (TextView) findViewById(R.id.tv_month13);
        tv_month14 = (TextView) findViewById(R.id.tv_month14);
        tv_month15 = (TextView) findViewById(R.id.tv_month15);
        tv_month16 = (TextView) findViewById(R.id.tv_month16);
        tv_month17 = (TextView) findViewById(R.id.tv_month17);
        tv_month18 = (TextView) findViewById(R.id.tv_month18);
        tv_month19 = (TextView) findViewById(R.id.tv_month19);
        tv_month20 = (TextView) findViewById(R.id.tv_month20);
        tv_month21 = (TextView) findViewById(R.id.tv_month21);
        tv_month22 = (TextView) findViewById(R.id.tv_month22);
        tv_month23 = (TextView) findViewById(R.id.tv_month23);
        tv_month24 = (TextView) findViewById(R.id.tv_month24);
        tv_month25 = (TextView) findViewById(R.id.tv_month25);
        tv_month26 = (TextView) findViewById(R.id.tv_month26);
        tv_month27 = (TextView) findViewById(R.id.tv_month27);
        tv_month28 = (TextView) findViewById(R.id.tv_month28);
        tv_month29 = (TextView) findViewById(R.id.tv_month29);
        tv_month30 = (TextView) findViewById(R.id.tv_month30);
        tv_month31 = (TextView) findViewById(R.id.tv_month31);

        btn_open = (Button) findViewById(R.id.btn_open);
        btn_close = (Button) findViewById(R.id.btn_close);

        tv_waterName1 = (TextView) findViewById(R.id.tv_waterName1);
        tv_waterId = (TextView) findViewById(R.id.tv_waterId);
        tv_rainStopSwitch = (TextView) findViewById(R.id.tv_rainStopSwitch);

        tv_s0 = (TextView) findViewById(R.id.tv_s0);
        tv_s1 = (TextView) findViewById(R.id.tv_s1);
        tv_s2 = (TextView) findViewById(R.id.tv_s2);

        deviceType = sPlantUitl.getWaterType(water.getWaterId());

        if (deviceType == 1) {

            View view = getLayoutInflater().inflate(R.layout.garden_1out_include, null);
            ll_waterContent.addView(view);

            ImageView img_water= (ImageView) view.findViewById(R.id.img_water);

            if (water.getWaterState()==1)
                img_water.setImageResource(R.mipmap.garden_ic_water1_online);
            else
                img_water.setImageResource(R.mipmap.garden_ic_water1_offline);

            tv_s1.setVisibility(View.INVISIBLE);
            tv_s2.setVisibility(View.INVISIBLE);

        } else if (deviceType == 2) {

            View view = getLayoutInflater().inflate(R.layout.garden_2out_include, null);
            ll_waterContent.addView(view);

            ImageView img_water= (ImageView) view.findViewById(R.id.img_water);

            if (water.getWaterState()==1)
                img_water.setImageResource(R.mipmap.garden_ic_water2_online);
            else
                img_water.setImageResource(R.mipmap.garden_ic_water2_offline);

            tv_switch1 = (TextView) findViewById(R.id.tv_switch1);
            img_switch1Selected = (ImageView) findViewById(R.id.img_switch1Selected);
            tv_s2.setVisibility(View.INVISIBLE);

        } else {

            View view = getLayoutInflater().inflate(R.layout.garden_3out_include, null);
            ll_waterContent.addView(view);

            ImageView img_water= (ImageView) view.findViewById(R.id.img_water);

            if (water.getWaterState()==1)
                img_water.setImageResource(R.mipmap.garden_ic_water3_online);
            else
                img_water.setImageResource(R.mipmap.garden_ic_water3_offline);

            tv_switch1 = (TextView) findViewById(R.id.tv_switch1);
            tv_switch2 = (TextView) findViewById(R.id.tv_switch2);

            img_switch1Selected = (ImageView) findViewById(R.id.img_switch1Selected);
            img_switch2Selected = (ImageView) findViewById(R.id.img_switch2Selected);
        }

        tv_switch0 = (TextView) findViewById(R.id.tv_switch0);
        img_switch0Selected = (ImageView) findViewById(R.id.img_switch0Selected);

        btn_goBack.setOnClickListener(this);
        tv_switch0.setOnClickListener(this);

        if (tv_switch1 != null)
            tv_switch1.setOnClickListener(this);
        if (tv_switch2 != null)
            tv_switch2.setOnClickListener(this);

        btn_open.setOnClickListener(this);
        btn_close.setOnClickListener(this);

        tv_s0.setOnClickListener(this);
        tv_s1.setOnClickListener(this);
        tv_s2.setOnClickListener(this);

        tv_month1.setOnClickListener(this);
        tv_month2.setOnClickListener(this);
        tv_month3.setOnClickListener(this);
        tv_month4.setOnClickListener(this);
        tv_month5.setOnClickListener(this);
        tv_month6.setOnClickListener(this);
        tv_month7.setOnClickListener(this);
        tv_month8.setOnClickListener(this);
        tv_month9.setOnClickListener(this);
        tv_month10.setOnClickListener(this);
        tv_month11.setOnClickListener(this);
        tv_month12.setOnClickListener(this);
        tv_month13.setOnClickListener(this);
        tv_month14.setOnClickListener(this);
        tv_month15.setOnClickListener(this);
        tv_month16.setOnClickListener(this);
        tv_month17.setOnClickListener(this);
        tv_month18.setOnClickListener(this);
        tv_month19.setOnClickListener(this);
        tv_month20.setOnClickListener(this);
        tv_month21.setOnClickListener(this);
        tv_month22.setOnClickListener(this);
        tv_month23.setOnClickListener(this);
        tv_month24.setOnClickListener(this);
        tv_month25.setOnClickListener(this);
        tv_month26.setOnClickListener(this);
        tv_month27.setOnClickListener(this);
        tv_month28.setOnClickListener(this);
        tv_month29.setOnClickListener(this);
        tv_month30.setOnClickListener(this);
        tv_month31.setOnClickListener(this);

        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {

            }
            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {

            }
        });

        init();
    }

    private LoadingDialog loadingDialog;

    private List<TimerWater> timerWaterList = new ArrayList<>();

    private void init() {

        sPlantClient = sPlantAsyncHttpClient.getInstance();
        loadingDialog = LoadingDialog.createDialog(this);

        garden_timeWater_adapter = new Garden_TimeWater_Adapter(Garden_Water_Activity.this, timerWaterList);

        lv_timerWaters.setAdapter(garden_timeWater_adapter);

        syncWaterSwitchState(true);
    }

    private void syncWaterSwitchState(boolean init)
    {
        RequestParams params = new RequestParams();

        sPlantClient.post(this, sPlantAsyncHttpClient.DEVICE_WATERING_STATUS, params, new sPlantJsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try
                {
                    if (response.getInt("succeed") == 1) {

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                handler.sendEmptyMessageDelayed(1,INV_TIME);

                Toast.makeText(Garden_Water_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });

        getWater(init);
    }
    private final int INV_TIME=5000;

    private sPlantAsyncHttpClient sPlantClient;

    //private RtTimerTask rtTimerTask;

    private void refreshDatas() {

        tv_waterName0.setText(water.getWaterName());
        tv_waterName1.setText(water.getWaterName());
        tv_waterId.setText(water.getWaterId());

        refreshSwitchsState();

        selectedSwitch(selectedSwitchNo);

//        if (rtTimerTask != null)
//            rtTimerTask.cancel();
//
//        rtTimerTask = new RtTimerTask();
//        if (water.getSwitchsTime() != null && water.getSwitchsTime().length > 0)
//        {
//            if (water.getSwitchsTime()[0] > 0) {
//                new Timer().schedule(rtTimerTask, 0, INTERVAL * 1000);
//                return;
//            }
//            if (water.getSwitchsTime().length > 1 && water.getSwitchsTime()[1] > 0) {
//                new Timer().schedule(rtTimerTask, 0, INTERVAL * 1000);
//                return;
//            }
//            if (water.getSwitchsTime().length > 2 && water.getSwitchsTime()[2] > 0) {
//                new Timer().schedule(rtTimerTask, 0, INTERVAL * 1000);
//                return;
//            }
//        }

    }

    private String timerCycle;

    private void selectedSwitch(int switchNo) {

        if (switchNo == 1) {
            selectedSwitchNo = 1;
            tv_s0.setBackground(new ColorDrawable(Color.parseColor("#74DA74")));
            tv_s1.setBackground(new ColorDrawable(Color.parseColor("#3A8F3A")));
            tv_s2.setBackground(new ColorDrawable(Color.parseColor("#3A8F3A")));

        } else if (switchNo == 2) {

            selectedSwitchNo = 2;
            tv_s0.setBackground(new ColorDrawable(Color.parseColor("#3A8F3A")));
            tv_s1.setBackground(new ColorDrawable(Color.parseColor("#74DA74")));
            tv_s2.setBackground(new ColorDrawable(Color.parseColor("#3A8F3A")));

        } else {
            selectedSwitchNo = 3;
            tv_s0.setBackground(new ColorDrawable(Color.parseColor("#3A8F3A")));
            tv_s1.setBackground(new ColorDrawable(Color.parseColor("#3A8F3A")));
            tv_s2.setBackground(new ColorDrawable(Color.parseColor("#74DA74")));
        }

         if (showSwitchsDaysCycle(switchNo)>0)
           selectMonthDay(selectedDay);

    }

    private boolean[] isTimeDays;

    private int showSwitchsDaysCycle(int switchNo)
    {
        timerCycle = "";
        isTimeDays=new boolean[31];
        selectedDay=0;

        List<TimerWater> timerWaterList = water.getTimerWaterList();

        if (timerWaterList != null)
        {
            for (TimerWater tw : timerWaterList)
            {
                if (tw.getSwitchNo() == switchNo)
                {
                    if (timerCycle.equals(""))
                        timerCycle = tw.getWaterCycle();
                    else {

                        String[] cycles = tw.getWaterCycle().split(",");
                        String[] curTimerCycles=timerCycle.split(",");

                        for (String s : cycles) {
                            boolean tf=false;
                            for (String ts:curTimerCycles)
                            {
                                if (ts.equals(s))
                                {
                                    tf=true;
                                    break;
                                }
                            }
                            if (!tf) {
                                timerCycle += "," + s;
                            }
                        }
                    }
                }
            }
        }

        if (timerCycle.equals("") == false) {

            try
            {
                daysCycle=timerCycle.split(",");
                if (selectedDay ==0)
                selectedDay = Integer.parseInt(timerCycle.substring(0, 1));

                if (daysCycle!=null)
                {
                    for (String d:daysCycle)
                    {
                        try
                        {
                            int day=Integer.parseInt(d);
                            isTimeDays[day-1]=true;
                        }
                        catch (Exception e)
                        {

                        }
                    }
                }

            }
            catch (Exception e)
            {

            }
        }
        return selectedDay;
    }

    private String[]  daysCycle;

    private void selectMonthDay(int day) {

        if (isTimeDays==null)
            return;
        boolean isSelected = false;

        if (isTimeDays[0]) {
            if (day == 1) {
                isSelected = true;
                tv_month1.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 1;
            } else
                tv_month1.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month1.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[1]) {
            if (day == 2) {
                isSelected = true;
                tv_month2.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 2;
            } else
                tv_month2.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month2.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[2]) {
            if (day == 3) {
                isSelected = true;
                tv_month3.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 3;
            } else
                tv_month3.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month3.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[3]) {
            if (day == 4) {
                isSelected = true;
                tv_month4.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 4;
            } else
                tv_month4.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month4.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[4]) {
            if (day == 5) {
                isSelected = true;
                tv_month5.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 5;
            } else
                tv_month5.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month5.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[5]) {
            if (day == 6) {
                isSelected = true;
                tv_month6.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 6;
            } else
                tv_month6.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month6.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[6]) {
            if (day == 7) {
                isSelected = true;
                tv_month7.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 7;
            } else
                tv_month7.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month7.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[7]) {
            if (day == 8) {
                isSelected = true;
                tv_month8.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 8;
            } else
                tv_month8.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month8.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[8]) {
            if (day == 9) {
                isSelected = true;
                tv_month9.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 9;
            } else
                tv_month9.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month9.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[9]) {
            if (day == 10) {
                isSelected = true;
                tv_month10.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 10;
            } else
                tv_month10.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month10.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[10]) {
            if (day == 11) {

                isSelected = true;
                tv_month11.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 11;

            } else
                tv_month11.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month11.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[11]) {

            if (day == 12) {
                isSelected = true;
                tv_month12.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 12;
            } else
                tv_month12.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month12.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[12]) {
            if (day == 13) {
                isSelected = true;
                tv_month13.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 13;
            } else
                tv_month13.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month13.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[13]) {
            if (day == 14) {
                isSelected = true;
                tv_month14.setBackgroundResource(R.color.garden_monthtable_bg_selected);

                selectedDay = 14;
            } else
                tv_month14.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month14.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[14]) {
            if (day == 15) {
                isSelected = true;
                tv_month15.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 15;
            } else
                tv_month15.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month15.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[15]) {
            if (day == 16) {
                isSelected = true;
                tv_month16.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 16;
            } else
                tv_month16.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month16.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[16]) {
            if (day == 17) {
                isSelected = true;
                tv_month17.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 17;
            } else
                tv_month17.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month17.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[17]) {
            if (day == 18) {
                isSelected = true;
                tv_month18.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 18;
            } else
                tv_month18.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month18.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[18]) {
            if (day == 19) {
                isSelected = true;
                tv_month19.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 19;
            } else
                tv_month19.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month19.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[19]) {
            if (day == 20) {
                isSelected = true;
                tv_month20.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 20;
            } else
                tv_month20.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month20.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[20]) {
            if (day == 21) {
                isSelected = true;
                tv_month21.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 21;
            } else
                tv_month21.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month21.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[21]) {
            if (day == 22) {
                isSelected = true;
                tv_month22.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 22;
            } else
                tv_month22.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month22.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[22]) {
            if (day == 23) {
                isSelected = true;
                tv_month23.setBackgroundResource(R.color.garden_monthtable_bg_selected);

                selectedDay = 23;
            } else
                tv_month23.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month23.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[23]) {
            if (day == 24) {
                isSelected = true;
                tv_month24.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 24;
            } else
                tv_month24.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month24.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[24]) {
            if (day == 25) {
                isSelected = true;
                tv_month25.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 25;
            } else
                tv_month25.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month25.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[25]) {
            if (day == 26) {
                isSelected = true;
                tv_month26.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 26;
            } else
                tv_month26.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month26.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[26]) {
            if (day == 27) {
                isSelected = true;
                tv_month27.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 27;
            } else
                tv_month27.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month27.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[27]) {
            if (day == 28) {
                isSelected = true;
                tv_month28.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 28;
            } else
                tv_month28.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month28.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[28]) {
            if (day == 29) {
                isSelected = true;
                tv_month29.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 29;
            } else
                tv_month29.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month29.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[29]) {
            if (day == 30) {
                isSelected = true;
                tv_month30.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 30;
            } else
                tv_month30.setBackgroundResource(R.color.garden_monthtable_bg_unselected);
        } else
            tv_month30.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isTimeDays[30]) {

            if (day == 31) {
                isSelected = true;
                tv_month31.setBackgroundResource(R.color.garden_monthtable_bg_selected);
                selectedDay = 31;
            } else
                tv_month31.setBackgroundResource(R.color.garden_monthtable_bg_unselected);

        } else
            tv_month31.setBackgroundResource(R.color.garden_monthtable_bg_normal);

        if (isSelected)
            getTimerWaterList();
    }

    private Garden_TimeWater_Adapter garden_timeWater_adapter;

    private void getTimerWaterList()  {

        if (selectedDay > 0)
        {
            RequestParams params = new RequestParams();
            params.put("day", selectedDay);
            params.put("switchNo", selectedSwitchNo);
            params.put("waterId", water.getWaterId());

            sPlantClient.get(sPlantAsyncHttpClient.GETDAYTIMERWATERS, params, new sPlantJsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    try
                    {
                        if (response.getInt("succeed") == 1) {

                            Gson gson = new Gson();
                            TimerWaterListBean timerWaterListBean = gson.fromJson(response.toString(), TimerWaterListBean.class);

                            timerWaterList.clear();
                            timerWaterList.addAll(timerWaterListBean.getTimerWaters());

                            garden_timeWater_adapter.setTimerWaterList(timerWaterList);

                            setListViewHeightBasedOnChildren(lv_timerWaters);

                            garden_timeWater_adapter.notifyDataSetChanged();

                        }
                    } catch (Exception e) {

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    Toast.makeText(Garden_Water_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    private int waterTime = 10;

    private void open() {

        waterTime = 10;
        getSelectedSwitchs();
        if (waterSwitchsNo.equals(""))
        {
            Toast.makeText(Garden_Water_Activity.this,"请选择开关",Toast.LENGTH_SHORT).show();
            return;
        }

        View outerView = LayoutInflater.from(this).inflate(R.layout.system_unit_wheel_view, null);
        WheelView wv = (WheelView) outerView.findViewById(R.id.wheel_view_wv);
        wv.setOffset(2);
        wv.setItems(getTimeData());
        wv.setSeletion(9);

        wv.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                String[] items = item.split(" ");
                waterTime = Integer.parseInt(items[0]);
            }
        });

        TextView tv = new TextView(this);
        tv.setText("请选择");
        tv.setTextSize(20);
        tv.setPadding(10, 10, 10, 10);
        tv.setGravity(Gravity.CENTER);
        tv.setTextColor(Color.parseColor("#ffaa66cc"));

        waterTimeDialog = new AlertDialog.Builder(this)
                .setCustomTitle(tv)
                .setView(outerView)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setwater();
                    }
                }).create();

        waterTimeDialog.show();

        WindowManager.LayoutParams params = waterTimeDialog.getWindow().getAttributes();
        params.width = (2 * DeviveMessages.getScreenInfo(this, getWindowManager()).getScreenWidth()) / 5;
        waterTimeDialog.getWindow().setAttributes(params);

    }

    private void close() {
        waterTime = 0;
        getSelectedSwitchs();
        if (waterSwitchsNo.equals(""))
        {
            Toast.makeText(Garden_Water_Activity.this,"请选择开关",Toast.LENGTH_SHORT).show();
            return;
        }

        final CustomDialog.Builder builder = new CustomDialog.Builder(Garden_Water_Activity.this);
        builder.setTitle("提示信息");
        builder.setMessage("您确定关闭给水？");
        builder.setPositiveButton(getString(R.string.system_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                setwater();
            }
        });
        builder.setNegativeButton(getString(R.string.system_cancel), new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();

    }

    private void getSelectedSwitchs()
    {
        waterSwitchsNo = "";
        if (img_switch0Selected.getVisibility() == View.VISIBLE) {
            waterSwitchsNo += "1";
        }
        if (img_switch1Selected != null) {
            if (img_switch1Selected.getVisibility() == View.VISIBLE) {
                waterSwitchsNo += ",2";
            }
        }
        if (img_switch2Selected != null) {
            if (img_switch2Selected.getVisibility() == View.VISIBLE) {
                waterSwitchsNo += ",3";
            }
        }
    }

    private  JSONArray selectSwitchs(int waterTime)
    {
        JSONArray waterTimes = new JSONArray();
        if (img_switch0Selected.getVisibility() == View.VISIBLE) {
            waterTimes.put(waterTime);
        } else
            waterTimes.put(-1);

        if (img_switch1Selected != null) {
            if (img_switch1Selected.getVisibility() == View.VISIBLE) {
                waterTimes.put(waterTime);
            } else
                waterTimes.put(-1);
        }
        if (img_switch2Selected != null) {
            if (img_switch2Selected.getVisibility() == View.VISIBLE) {
                waterTimes.put(waterTime);
            } else
                waterTimes.put(-1);
        }
        return waterTimes;
    }

    private void setwater() {

            final JSONArray waterTimesAry=selectSwitchs(waterTime);
            btn_open.setEnabled(false);
            btn_close.setEnabled(false);
            waterOperation(waterTimesAry);

    }

    private void getWater(final boolean isInit) {

        RequestParams params = new RequestParams();
        params.put("searchDevId", water.getWaterId());

        sPlantClient.get(sPlantAsyncHttpClient.GETWATERDEVICES, params, new sPlantJsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {

                        try
                        {
                            handler.sendEmptyMessageDelayed(1,INV_TIME);

                            materialRefreshLayout.finishRefresh();

                            if (response.getInt("succeed") == 1)
                            {
                                Gson gson = new Gson();
                                WaterListBean waterListBean = gson.fromJson(response.toString(), WaterListBean.class);

                                if (waterListBean.getWaterList() != null && waterListBean.getWaterList().size() > 0) {

                                    water = waterListBean.getWaterList().get(0);

                                    refreshDatas();

                                    if (isInit)
                                        selectedSwitch(1);
                                }

                            }

                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        handler.sendEmptyMessageDelayed(1,INV_TIME);
                        materialRefreshLayout.finishRefresh();
                        Toast.makeText(Garden_Water_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }
                }
        );

    }

    private void waterSuccesss() {

        if (waterSwitchsNo.contains("1")) {

            if (water.getSwitchsTime() != null && water.getSwitchsTime().length > 0) {
                water.getSwitchsTime()[0] = waterTime * 60;
                tv_switch0.setBackgroundResource(R.color.garden_switch_on);
            } else
                tv_switch0.setBackgroundResource(R.color.garden_switch_off);

        }
        if (waterSwitchsNo.contains("2")) {

            if (water.getSwitchsTime() != null && water.getSwitchsTime().length > 1) {
                water.getSwitchsTime()[1] = waterTime * 60;
                tv_switch0.setBackgroundResource(R.color.garden_switch_on);
            } else
                tv_switch0.setBackgroundResource(R.color.garden_switch_off);

        }
        if (waterSwitchsNo.contains("3")) {

            if (water.getSwitchsTime() != null && water.getSwitchsTime().length > 2) {
                water.getSwitchsTime()[2] = waterTime * 60;
                tv_switch0.setBackgroundResource(R.color.garden_switch_on);
            } else
                tv_switch0.setBackgroundResource(R.color.garden_switch_off);

        }

        refreshSwitchsState();

//        if (rtTimerTask != null)
//            rtTimerTask.cancel();
//
//        rtTimerTask = new RtTimerTask();
//
//        new Timer().schedule(rtTimerTask, 0, INTERVAL * 1000);

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                refreshSwitchsState();
            }
            else if (msg.what==1){
                if (waterOpertion==false)
                getWater(false);
            }
        }
    };

    private int waterSwitchState=0;//浇灌的开关状态

    private void refreshSwitchsState() {

        if (water.getSwitchsTime() != null)
        {
            if (water.getSwitchsTime().length > 0) {

                int st1 = water.getSwitchsTime()[0] / 60;

                if (water.getSwitchsTime()[0]%60>0)
                    st1+=1;

                if (water.getSwitchsTime()[0] > 0) {
                    tv_switch0.setText(String.valueOf(st1) + "分钟");
                    tv_switch0.setBackgroundResource(R.color.garden_switch_on);

                } else {

                    if (waterSwitchState==0)
                    {
                        water.getSwitchsTime()[0] = 0;
                        tv_switch0.setText("开关1");
                        tv_switch0.setBackgroundResource(R.color.garden_switch_off);
                    }

                }

            }

            if (water.getSwitchsTime().length > 1 && deviceType == 2) {

                int st2 = water.getSwitchsTime()[1] / 60;
                if (water.getSwitchsTime()[1] > 0) {

                    if (water.getSwitchsTime()[1]%60>0)
                        st2+=1;

                    tv_switch1.setText(String.valueOf(st2) + "分钟");
                    tv_switch1.setBackgroundResource(R.color.garden_switch_on);

                } else {

                    if (waterSwitchState==0)
                    {
                        water.getSwitchsTime()[1] = 0;
                        tv_switch1.setText("开关2");
                        tv_switch1.setBackgroundResource(R.color.garden_switch_off);
                    }


                }
            }
            if (water.getSwitchsTime().length > 2 && deviceType == 3) {

                int st2 = water.getSwitchsTime()[1] / 60;
                if (water.getSwitchsTime()[1] > 0) {

                    if (water.getSwitchsTime()[1]%60>0)
                        st2+=1;

                    tv_switch1.setText(String.valueOf(st2) + "分钟");
                    tv_switch1.setBackgroundResource(R.color.garden_switch_on);

                } else {

                    if (waterSwitchState==0)
                    {
                        water.getSwitchsTime()[1] = 0;
                        tv_switch1.setText("开关2");
                        tv_switch1.setBackgroundResource(R.color.garden_switch_off);
                    }


                }

                int st3 = water.getSwitchsTime()[2] / 60;
                if (water.getSwitchsTime()[2] > 0) {

                    if (water.getSwitchsTime()[2]%60>0)
                        st3+=1;

                    tv_switch2.setText(String.valueOf(st3) + "分钟");
                    tv_switch2.setBackgroundResource(R.color.garden_switch_on);

                } else {

                    if (waterSwitchState==0)
                    {
                        water.getSwitchsTime()[2] = 0;
                        tv_switch2.setText("开关3");
                        tv_switch2.setBackgroundResource(R.color.garden_switch_off);
                    }


                }
            }
        }

    }

    private final int INTERVAL = 1;

    private class RtTimerTask extends TimerTask {
        @Override
        public void run() {
            if (water.getSwitchsTime() != null) {
                boolean isRefresh = false;
                int closedCount = 0;
                if (water.getSwitchsTime().length > 0) {

                    if (water.getSwitchsTime()[0] > 0) {
                        water.getSwitchsTime()[0] -= INTERVAL;
                        if (water.getSwitchsTime()[0] % 60 == 0)
                            isRefresh = true;
                    } else
                        closedCount++;
                }
                if (water.getSwitchsTime().length > 1) {

                    if (water.getSwitchsTime()[1] > 0) {
                        water.getSwitchsTime()[1] -= INTERVAL;
                        if (water.getSwitchsTime()[1] % 60 == 0)
                            isRefresh = true;
                    } else
                        closedCount++;
                }
                if (water.getSwitchsTime().length > 2) {

                    if (water.getSwitchsTime()[2] > 0) {
                        water.getSwitchsTime()[2] -= INTERVAL;
                        if (water.getSwitchsTime()[2] % 60 == 0)
                            isRefresh = true;
                    } else
                        closedCount++;
                }
                if (isRefresh)
                    handler.sendEmptyMessage(0);

                if (deviceType == 1 && closedCount == 1) {
                    cancel();
                } else if (deviceType == 2 && closedCount == 2) {
                    cancel();
                } else if (deviceType == 3 && closedCount == 3) {
                    cancel();
                }
            }
        }

    }

    private boolean waterOpertion=false;//是否浇水操作

    private void waterOperation(JSONArray jsonArray) {

        waterOpertion=true;

        sPlantRequestParams params = new sPlantRequestParams();
        params.putParams("waterId", water.getWaterId());
        params.putParams("switchsTime", jsonArray);
        params.putParams("waitAck", false);


//        if (loadingDialog != null && loadingDialog.isShowing() == false) {
//            loadingDialog.show();
//            loadingDialog.setMessage("等待设备回应……");
//        }

        sPlantClient.post(this, sPlantAsyncHttpClient.SETWATER, params, new sPlantJsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try
                        {
                            waterOpertion=false;
                            Toast.makeText(Garden_Water_Activity.this, response.getString("message"), Toast.LENGTH_SHORT).show();

                            if (response.getInt("succeed") == 1) {

//                                if (waterTime > 0)
//                                    Toast.makeText(Garden_Water_Activity.this, "打开成功！", Toast.LENGTH_SHORT).show();
//                                else
//                                    Toast.makeText(Garden_Water_Activity.this, "关闭成功！", Toast.LENGTH_SHORT).show();

                             //   waterSuccesss();

                                waitingState();

                            }
//                            else if (response.getInt("succeed") == 0) {
//
//                                if (waterTime > 0)
//                                    Toast.makeText(Garden_Water_Activity.this, "打开失败！", Toast.LENGTH_SHORT).show();
//                                else
//                                    Toast.makeText(Garden_Water_Activity.this, "关闭失败！", Toast.LENGTH_SHORT).show();
//
//                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        btn_open.setEnabled(true);
                        btn_close.setEnabled(true);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        btn_open.setEnabled(true);
                        btn_close.setEnabled(true);
                        waterOpertion=false;
                        Toast.makeText(Garden_Water_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void waitingState()
    {
        if(waterSwitchsNo.contains("1"))
        {
            tv_switch0.setText("等待…");
        }
        else if (waterSwitchsNo.contains("2"))
        {
            if (tv_switch1!=null)
                tv_switch1.setText("等待…");
        }
        else if (waterSwitchsNo.contains("3"))
        {
            if (tv_switch2!=null)
                tv_switch2.setText("等待…");
        }
    }

    private Dialog waterTimeDialog = null;

    private List<String> mDatas = new ArrayList<>();

    private List<String> getTimeData() {
        for (int i = 1; i <= 10; i++) {
            mDatas.add(i + " 分钟");
        }
        for (int i = 15; i <= 30; i+=5) {
            mDatas.add(i + " 分钟");
        }
        for (int i = 40; i <= 60; i+=10) {
            mDatas.add(i + " 分钟");
        }
        return mDatas;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_goBack:
                EventBus.getDefault().post(new PostWater(water));
                finish();
                break;
            case R.id.tv_switch0:
                if (img_switch0Selected.getVisibility() == View.VISIBLE)
                    img_switch0Selected.setVisibility(View.GONE);
                else
                    img_switch0Selected.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_switch1:
                if (img_switch1Selected.getVisibility() == View.VISIBLE)
                    img_switch1Selected.setVisibility(View.GONE);
                else
                    img_switch1Selected.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_switch2:
                if (img_switch2Selected.getVisibility() == View.VISIBLE)
                    img_switch2Selected.setVisibility(View.GONE);
                else
                    img_switch2Selected.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_open:
                open();
                break;
            case R.id.btn_close:
                close();
                break;
            case R.id.tv_s0:
                selectedSwitch(1);
                break;
            case R.id.tv_s1:
                selectedSwitch(2);
                break;
            case R.id.tv_s2:
                selectedSwitch(3);
                break;
            case R.id.tv_month1:
                selectMonthDay(1);
                break;
            case R.id.tv_month2:
                selectMonthDay(2);
                break;
            case R.id.tv_month3:
                selectMonthDay(3);
                break;
            case R.id.tv_month4:
                selectMonthDay(4);
                break;
            case R.id.tv_month5:
                selectMonthDay(5);
                break;
            case R.id.tv_month6:
                selectMonthDay(6);
                break;
            case R.id.tv_month7:
                selectMonthDay(7);
                break;
            case R.id.tv_month8:
                selectMonthDay(8);
                break;
            case R.id.tv_month9:
                selectMonthDay(9);
                break;
            case R.id.tv_month10:
                selectMonthDay(10);
                break;
            case R.id.tv_month11:
                selectMonthDay(11);
                break;
            case R.id.tv_month12:
                selectMonthDay(12);
                break;
            case R.id.tv_month13:
                selectMonthDay(13);
                break;
            case R.id.tv_month14:
                selectMonthDay(14);
                break;
            case R.id.tv_month15:
                selectMonthDay(15);
                break;
            case R.id.tv_month16:
                selectMonthDay(16);
                break;
            case R.id.tv_month17:
                selectMonthDay(17);
                break;
            case R.id.tv_month18:
                selectMonthDay(18);
                break;
            case R.id.tv_month19:
                selectMonthDay(19);
                break;
            case R.id.tv_month20:
                selectMonthDay(20);
                break;
            case R.id.tv_month21:
                selectMonthDay(21);
                break;
            case R.id.tv_month22:
                selectMonthDay(22);
                break;
            case R.id.tv_month23:
                selectMonthDay(23);
                break;
            case R.id.tv_month24:
                selectMonthDay(24);
                break;
            case R.id.tv_month25:
                selectMonthDay(25);
                break;
            case R.id.tv_month26:
                selectMonthDay(26);
                break;
            case R.id.tv_month27:
                selectMonthDay(27);
                break;
            case R.id.tv_month28:
                selectMonthDay(28);
                break;
            case R.id.tv_month29:
                selectMonthDay(29);
                break;
            case R.id.tv_month30:
                selectMonthDay(30);
                break;
            case R.id.tv_month31:
                selectMonthDay(31);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            EventBus.getDefault().post(new PostWater(water));
        }
        return super.onKeyDown(keyCode, event);
    }

}
